package com.sofwin.interceptor;

import com.sofwin.Constants;
import com.sofwin.mapper.SMonitorMapper;
import com.sofwin.pojo.SMonitor;
import com.sofwin.pojo.SUser;
import com.sofwin.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
@Component
public class MonitorInterceptor implements HandlerInterceptor {

    @Autowired
    private SMonitorMapper monitorMapper;

    private long beginDate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        beginDate = System.currentTimeMillis();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求时间
        String requestDate = String.valueOf(System.currentTimeMillis() - beginDate);
        // 用户id
        HttpSession session = request.getSession();
        SUser user = (SUser)session.getAttribute(Constants.CURR_USER);
        Integer userId = user.getId();
        // 访问时间
        String visitDate = DateUtil.getDateStr(new Date(),"yyyy-MM-dd HH:mm:ss");
        // 请求的ip
        String visitIp = request.getRemoteAddr();
        // 请求的url
        String visitUrl = request.getRequestURI();
        // insert
        SMonitor sMonitor = new SMonitor(userId,visitUrl,visitDate,requestDate,visitIp);
        monitorMapper.insertSelective(sMonitor);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
